"""
订单 Mock 服务
模拟订单查询 API，用于演示目的
"""

import json
import time
import logging
from flask import Flask, jsonify, request
from datetime import datetime, timedelta

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)

# 模拟订单数据
MOCK_ORDERS = {
    "ORD20250401": {
        "order_id": "ORD20250401",
        "status": "已付款",
        "amount": "299.00",
        "date": "2024-04-01",
        "customer": "张三",
        "items": ["商品A", "商品B"],
        "refundable": True,
        "refund_deadline": (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
    },
    "ORD20250402": {
        "order_id": "ORD20250402",
        "status": "待发货",
        "amount": "159.50",
        "date": "2024-04-02",
        "customer": "李四",
        "items": ["商品C"],
        "refundable": False,
        "refund_deadline": None
    },
    "ORD20250403": {
        "order_id": "ORD20250403",
        "status": "已发货",
        "amount": "89.99",
        "date": "2024-04-03",
        "customer": "王五",
        "items": ["商品D", "商品E"],
        "refundable": True,
        "refund_deadline": (datetime.now() + timedelta(days=7)).strftime("%Y-%m-%d")
    },
    "ORD20250404": {
        "order_id": "ORD20250404",
        "status": "已完成",
        "amount": "499.00",
        "date": "2024-04-04",
        "customer": "赵六",
        "items": ["商品F", "商品G", "商品H"],
        "refundable": True,
        "refund_deadline": (datetime.now() + timedelta(days=15)).strftime("%Y-%m-%d")
    },
    "ORD20250405": {
        "order_id": "ORD20250405",
        "status": "已取消",
        "amount": "199.99",
        "date": "2024-04-05",
        "customer": "孙七",
        "items": ["商品I"],
        "refundable": False,
        "refund_deadline": None
    }
}


@app.route('/')
def index():
    """服务根路径"""
    return jsonify({
        "service": "Order Mock Service",
        "version": "1.0.0",
        "description": "模拟订单查询API服务",
        "endpoints": {
            "/order/<order_id>": "查询订单信息",
            "/orders": "获取所有订单",
            "/health": "健康检查"
        }
    })


@app.route('/health')
def health():
    """健康检查"""
    return jsonify({
        "status": "healthy",
        "timestamp": time.time(),
        "total_orders": len(MOCK_ORDERS)
    })


@app.route('/orders')
def get_all_orders():
    """获取所有订单"""
    return jsonify({
        "success": True,
        "data": list(MOCK_ORDERS.values()),
        "total": len(MOCK_ORDERS)
    })


@app.route('/order/<order_id>')
def get_order(order_id):
    """查询单个订单"""
    start_time = time.time()

    try:
        # 查找订单
        order = MOCK_ORDERS.get(order_id)

        if order:
            # 模拟处理时间
            processing_time = time.time() - start_time

            logger.info(f"Order found: {order_id}, processing_time: {processing_time:.2f}s")

            return jsonify({
                "success": True,
                "data": order,
                "processing_time": f"{processing_time:.2f}s"
            })
        else:
            # 订单不存在
            processing_time = time.time() - start_time

            logger.warning(f"Order not found: {order_id}")

            return jsonify({
                "success": False,
                "error": "订单不存在",
                "order_id": order_id,
                "processing_time": f"{processing_time:.2f}s"
            }), 404

    except Exception as e:
        processing_time = time.time() - start_time

        logger.error(f"Error processing order {order_id}: {e}")

        return jsonify({
            "success": False,
            "error": f"服务器内部错误: {str(e)}",
            "order_id": order_id,
            "processing_time": f"{processing_time:.2f}s"
        }), 500


@app.route('/order/<order_id>/refund', methods=['POST'])
def process_refund(order_id):
    """处理退款请求"""
    start_time = time.time()

    try:
        order = MOCK_ORDERS.get(order_id)

        if not order:
            return jsonify({
                "success": False,
                "error": "订单不存在",
                "order_id": order_id
            }), 404

        if not order.get("refundable"):
            return jsonify({
                "success": False,
                "error": "该订单不支持退款",
                "order_id": order_id,
                "status": order.get("status")
            }), 400

        # 模拟退款处理
        refund_id = f"REF{order_id}_{int(time.time())}"

        processing_time = time.time() - start_time

        logger.info(f"Refund processed: {refund_id} for order {order_id}")

        return jsonify({
            "success": True,
            "data": {
                "refund_id": refund_id,
                "order_id": order_id,
                "amount": order.get("amount"),
                "status": "退款处理中",
                "estimated_completion": (datetime.now() + timedelta(days=3)).strftime("%Y-%m-%d")
            },
            "processing_time": f"{processing_time:.2f}s"
        })

    except Exception as e:
        processing_time = time.time() - start_time

        logger.error(f"Error processing refund for {order_id}: {e}")

        return jsonify({
            "success": False,
            "error": f"退款处理失败: {str(e)}",
            "order_id": order_id
        }), 500


@app.errorhandler(404)
def not_found(error):
    """处理404错误"""
    return jsonify({
        "success": False,
        "error": "接口不存在",
        "path": request.path
    }), 404


@app.errorhandler(500)
def internal_error(error):
    """处理500错误"""
    logger.error(f"Internal server error: {error}")
    return jsonify({
        "success": False,
        "error": "服务器内部错误"
    }), 500


if __name__ == '__main__':
    # 开发环境运行
    app.run(
        host='0.0.0.0',
        port=5000,
        debug=True
    )
